from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
import base64
import time
from appium.webdriver.common.touch_action import TouchAction

caps = {
    "platformName": "Android",
    "automationName": "uiautomator2",
    "udid": "127.0.0.1:9611",
    "appPackage": "com.zhiliaoapp.musically",
    "appActivity": "com.ss.android.ugc.aweme.main.MainActivity",
    "noReset": True,
    "chromedriverExecutable":"/root/chromedriver/chromedriver",
    "autoGrantPermissions": True,
    "uiautomator2ServerLaunchTimeout": 120000,  # 增加服务器启动超时
    "adbExecTimeout": 120000,  # 增加ADB执行超时
}

driver = webdriver.Remote("http://127.0.0.1:4723", caps)


def swipe_up(driver, duration=100):
    """使用兼容的滑动方法"""
    try:
        window_size = driver.get_window_size()
        screen_width = window_size['width']
        screen_height = window_size['height']

        # 计算起始点和滑动参数
        start_x = screen_width * 0.5  # 宽度50%
        start_y = screen_height * 0.8  # 高度80%
        end_y = screen_height * 0.2  # 高度20%
        end_x= screen_width * 0.5
        driver.swipe(start_x, start_y, end_x, end_y, duration)
        # 计算滑动距离（像素）
        # swipe_distance = start_y - end_y
        #
        # # 尝试使用支持的移动端方法
        # driver.execute_script("mobile: swipeGesture", {
        #     "left": start_x - 50,  # 区域起始X坐标（中心点左侧50像素）
        #     "top": start_y - 50,  # 区域起始Y坐标（中心点上方50像素）
        #     "width": 100,  # 区域宽度100像素
        #     "height": 100,  # 区域高度100像素
        #     "direction": "up",
        #     "percent": swipe_distance / 100,  # 滑动距离相对于区域高度的比例
        #     "speed": 1500
        # })
    except Exception as e:
        print(f"滑动方法1失败: {e}")
        try:
            driver.execute_script("mobile: scroll", {"direction": "down"})
        except Exception as e3:
            print(f"所有滑动方法都失败: {e3}")
        # try:
        #     # 方法2: 使用传统的swipe方法
        #     driver.swipe(start_x, start_y, end_x, end_y, duration)
        # except Exception as e2:
        #     print(f"滑动方法2也失败: {e2}")
        #     # 方法3: 使用scroll方法作为备选
# 等待 WebView 加载并切换 context
def switch_to_webview(driver, timeout=10):
    """等待 WebView 出现并切换 context"""
    for i in range(timeout):
        contexts = driver.contexts  # 获取所有 context
        print(f"当前可用 contexts: {contexts}")
        # 通常 webview 的名字包含 "WEBVIEW" 或 "WEBVIEW_chrome" 等
        webview_contexts = [c for c in contexts if 'WEBVIEW' in c.upper()]
        if len(webview_contexts) > 0:
            # 选择一个 webview context（如果不止一个，也可以具体匹配包名或包含 google 的某些关键词）
            target = webview_contexts[-1]
            driver.switch_to.context(target)
            print(f"切换到 WebView context: {target}")
            return True
        time.sleep(1)
    raise TimeoutException("没有找到 WebView 上下文切换失败")

# 启动指定 Activity
driver.start_activity("com.zhiliaoapp.musically", "com.ss.android.ugc.aweme.main.MainActivity")
#//android.widget.Button[@text="Agree and continue"]
try:
    agree_term = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((
        AppiumBy.XPATH,
        '//android.widget.Button[@text="Agree and continue"]'
    )))
    agree_term.click()
    print("点击同意隐私协议")
    # 等待并处理权限提示框

except (TimeoutException, NoSuchElementException):
    print("没有找到同意隐私协议按钮")
try:
    allow_notify = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((
        AppiumBy.XPATH,
        '//android.widget.Button[@resource-id="com.android.permissioncontroller:id/permission_allow_button"]'
    )))
    allow_notify.click()
    print("允许tiktok推送通知")
    # 等待并处理权限提示框

except (TimeoutException, NoSuchElementException):
    print("没有找到允许tiktok推送通知按钮")

try:
    element_rqe = WebDriverWait(driver, 5).until(EC.presence_of_element_located((
        AppiumBy.XPATH,
        '//android.widget.TextView[@resource-id="com.zhiliaoapp.musically:id/rqe"]'
    )))
    print("找到了 rqe 元素，准备滑动")
    swipe_up(driver)
except TimeoutException:
    print("在等待时间内没找到 rqe 元素，不滑动")

try:
    print("等待 Profile 按钮")
    # 策略1: 先尝试使用已知的resource-id（最快）
    try:
        profile_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((
            AppiumBy.XPATH, '//android.widget.FrameLayout[@content-desc="Profile"]'
        )))
        print("通过ID找到Profile按钮")
    except:
        # 策略2: 尝试使用文本查找（中文或英文）
        try:
            profile_button = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((
                AppiumBy.XPATH, '//android.widget.TextView[@text="Profile" or @text="我" or @text="个人资料"]'
            )))
            print("通过文本找到Profile按钮")
        except:
            # 策略3: 使用content-description
            profile_button = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((
                AppiumBy.XPATH, '//*[contains(@content-desc, "Profile") or contains(@content-desc, "我")]'
            )))
            print("通过content-desc找到Profile按钮")

    # 直接点击，避免额外的属性检查
    print("找到了Profile按钮，准备点击")
    profile_button.click()
    print("点击Profile按钮成功")
    google_login_button = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((
        AppiumBy.XPATH, '//android.widget.Button[@content-desc="Continue with Google"]'
    )))
    google_login_button.click()
    #//android.widget.Button[@text="NEXT"]
    try:
        next_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((
            AppiumBy.XPATH, '//android.widget.Button[@text="NEXT"]'
        )))
        print("找到next按钮")
        window_size = driver.get_window_size()
        screen_width = window_size['width']
        screen_height = window_size['height']
        print("window_size: ", window_size)
        driver.execute_script("mobile: shell", {
            "command": "input",
            "args": ["tap", "800","1080"]
        })
        time.sleep(1)
        driver.execute_script("mobile: shell", {
            "command": "input",
            "args": ["text", "tuqiang19921002@gmail.com"]
        })
        time.sleep(1)
        next_button.click()
        try:
            next_button2 = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((
                AppiumBy.XPATH, '//android.widget.Button[@text="NEXT"]'
            )))
            driver.execute_script("mobile: shell", {
                "command": "input",
                "args": ["tap", int(screen_width/2), int(screen_height*0.346)]
            })
            time.sleep(1)
            driver.execute_script("mobile: shell", {
                "command": "input",
                "args": ["text", "tuqiang1992"]
            })
            time.sleep(1)
            next_button2.click()
            try:
                agree_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((
                    AppiumBy.XPATH, '//android.widget.Button[@text="I agree"]'
                )))
                agree_button.click()
                print("点击同意协议按钮")
                try:
                    next_button3 = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((
                        AppiumBy.XPATH, '//android.widget.Button[@text="ACCEPT"]'
                    )))
                    next_button3.click()
                    print("点击next3按钮")
                except:
                    print("未找到next3按钮")
            except:
                print("未找到同意协议按钮")
        except:
            print("未找到next2按钮")

    except:
        print("未找到next按钮")
except (TimeoutException, NoSuchElementException):
    print("没有找到Profile按钮")

driver.quit()
